package com.ling.luo.serverweb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 开启 WebSocket 服务
 *
 * @author luohoujian
 * @date 2020.11.14
 */
@ServerEndpoint("/iceserver/{userId}")
@Component
public class WebSocketServer {
    private Logger logger = Logger.getLogger(WebSocketServer.class);

    /**
     * 用来存储每个客户端的 WebSocket 对象
     */
    private ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<String, WebSocketServer>();

    /**
     * 用来记录当前在线连接数，应该把它设计成线程安全
     */
    private AtomicInteger onlineCount = new AtomicInteger(0);
    private Session session;
    private String userId;

    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen (Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            // 加入 map 中
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            // 在线数加 1
            onlineCount.getAndAdd(1);
        }
        logger.info("用户连接：" + userId + "，当前在线人数为：" + onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose () {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            onlineCount.getAndDecrement();
        }
        logger.info("用户退出：" + userId + "，当前在线人数为：" + onlineCount.get());
    }

    @OnMessage
    public void onMessage (String message, Session session) {
        logger.info("用户消息：" + userId + "，报文：" + message);
        JSONObject jsonObject = JSON.parseObject(message);
        jsonObject.put("fromUserId", this.userId);
        String toUserId = jsonObject.getString("toUserId");
        webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
    }

    /**
     *
     * @param session
     * @param error
     */
    public void onError (Session session, Throwable error) {
        logger.info("用户错误：" + this.userId + "，原因：" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     * @param message
     */
    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendInfo(String message, @PathParam("userId") String userId) {
        logger.info("发送消息到：" + userId + "，报文：" + message);
        webSocketMap.get(userId).sendMessage(message);
    }




























}
